/*
 * Copyright 2011 Daniel Krieg
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.code.csf;

public abstract class ServiceProxy<ServiceType> {
    private final ServiceTemplate<ServiceType> serviceTemplate;

    protected ServiceProxy(ServiceTemplate<ServiceType> serviceTemplate) {
        this.serviceTemplate = serviceTemplate;
    }

    protected final ServiceTemplate<ServiceType> getServiceTemplate() {
        return serviceTemplate;
    }

    protected <E extends Throwable, ResponseType> ResponseType execute(Class<E> throwable, ServiceAdapter<ResponseType, ServiceType> serviceAdapter) throws E {
        try {
            return getServiceTemplate().execute(serviceAdapter);
        } catch (Throwable e) {
            throw translateException(throwable, e);
        }
    }

    @SuppressWarnings("unchecked")
    protected <E extends Throwable> E translateException(Class<E> type, Throwable exception) {
        assert type != null && exception != null;
        if (type.isAssignableFrom(exception.getClass())) {
            return (E) exception;
        }

        E throwable;
        try {
            if (exception instanceof ServiceException) {
                Throwable cause = exception.getCause();
                if (cause == null) {
                    throwable = type.getConstructor(String.class).newInstance(exception.getMessage());
                } else if (type.isAssignableFrom(cause.getClass())) {
                    return (E) exception;
                } else {
                    throwable = type.getConstructor(Throwable.class).newInstance(cause);
                }
            } else {
                throwable = type.getConstructor(Throwable.class).newInstance(exception);
            }
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return throwable;
    }
}
